from goods.models import GoodCategoryVisit
from .serializers import CateGoryModelSerializer
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from users.models import User
from rest_framework.response import Response
from datetime import date, timedelta
from orders.models import OrderInfo


# 获取用户总数
class UserTotalCountView(APIView):
    def get(self, request):
        # 获取用户总数
        users = User.objects.count()
        # users = User.objects.filter(is_staff=False, is_superuser=False).count()  # 过滤管理员
        # 返回响应
        return Response({"count": users})


# 获取日增用户数
class UserDayIncrementView(APIView):
    def get(self, request):
        # 获取日增用户数----> datejouned大于当天时间零点
        day_incre_user = User.objects.filter(date_joined__gte=date.today()).count()
        # 返回响应
        return Response({"count": day_incre_user})


# 获取日活用户数
class UserDayActiveView(APIView):
    def get(self, request):
        # 获取日活用户数----> lastlogin大于等于今天
        day_active_user = User.objects.filter(last_login__gte=date.today()).count()
        # 返回响应
        return Response({"count": day_active_user})


# 获取下单用户数
class UserDayOrdersView(APIView):
    def get(self, request):
        # 获取下单用户数----> 订单信息表user_id用户数, (订单:用户----->多:一)
        # 进行查询去重获取下单用户数
        order_user_count_all = OrderInfo.objects.all()  # 查询所有字段
        order_user_count = order_user_count_all.values('user').distinct().count()  # 对 user 字段进行去重查询
        # 返回响应
        return Response({"count": order_user_count})


# 获取月新增用户数
class UserMonthIncrementView(APIView):
    def get(self, request):
        # 获取月新增用户数-----> (当月内创建的用户)用户创建时候的月份等于当前月份
        # pass



        # 获取近30天新增用户数
        day_user_list = []
        # 获取当天日期
        today = date.today()
        # 获取30天前的日期
        old_day = today - timedelta(days=29)
        # 遍历得出30天内每日的新增用户数
        for i in range(0, 30):
            # 30天前的日期
            current_day = old_day + timedelta(days=i)
            # 30天前的日期的下一天
            next_day = old_day + timedelta(days=i + 1)
            # 查询每一天的新增用户数
            count = User.objects.filter(date_joined__gte=current_day, date_joined__lt=next_day).count()
            # 将每一天的count和date添加到列表中
            day_user_list.append({"count": count, "date": current_day})
        # 返回响应
        return Response(day_user_list)


# 获取商品分类日访问量
class UserGoodDayCountView(GenericAPIView):
    # 获取通用序列化器
    serializer_class = CateGoryModelSerializer

    def get(self, request):
        # 获取当天访问的商品分类数据对象
        today = date.today()
        goods_day_visit = GoodCategoryVisit.objects.filter(date__gte=today).all()
        # 创建序列化器对象
        serializer = self.get_serializer(instance=goods_day_visit, many=True)
        # 返回响应
        return Response(serializer.data)
